package com.sunzr0119.conventioncentertemplatebackend.service.impl;

import com.sunzr0119.conventioncentertemplatebackend.service.CaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.data.redis.core.StringRedisTemplate;

@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}") // 发送者邮箱
    private String fromEmail;

    @Autowired
    private StringRedisTemplate redisTemplate; // 使用 Redis 存储验证码

    @Override
    public Map<String, String> generateImgCaptcha() {
        // 1. 生成随机验证码
        String captchaText = generateRandomText(4);

        // 2. 生成验证码图片
        BufferedImage image = createCaptchaImage(captchaText);

        // 3. 转换为 Base64
        String base64Image = encodeImageToBase64(image);

        // 4. 返回数据
        Map<String, String> result = new HashMap<>();
        result.put("captcha", captchaText);
        result.put("image", "data:image/png;base64," + base64Image);
        return result;
    }

    /**
     * 生成随机验证码（默认4位）
     */
    private String generateRandomText(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuilder text = new StringBuilder();
        for (int i = 0; i < length; i++) {
            text.append(chars.charAt(random.nextInt(chars.length())));
        }
        return text.toString();
    }

    /**
     * 生成验证码图片
     */
    private BufferedImage createCaptchaImage(String text) {
        int width = 160, height = 45;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);

        // 设置字体
        g.setFont(new Font("Arial", Font.BOLD, 30));
        g.setColor(Color.BLACK);
        g.drawString(text, 30, 40);

        // 画干扰线
        Random random = new Random();
        g.setColor(Color.GRAY);
        for (int i = 0; i < 5; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g.drawLine(x1, y1, x2, y2);
        }

        g.dispose();
        return image;
    }

    /**
     * 转换图片为 Base64
     */
    private String encodeImageToBase64(BufferedImage image) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            return Base64.getEncoder().encodeToString(baos.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }




    @Override
    public ResponseEntity<String> sendEmailCaptcha(String toEmail, String captcha) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(toEmail);
            message.setSubject("您的验证码");
            message.setText("您的验证码是：" + captcha + "，有效期为5分钟，请尽快使用。");

            mailSender.send(message);
            // 将验证码存入 Redis，设定有效期（例如 5 分钟）
            redisTemplate.opsForValue().set("captcha:" + toEmail, captcha, 5, TimeUnit.MINUTES);
            String storedCaptcha = redisTemplate.opsForValue().get("captcha:" + toEmail);
            if (storedCaptcha == null) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("验证码redis缓存失败！T.T");
            }else {
                return ResponseEntity.ok("验证码缓存成功："+storedCaptcha);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        }
    }
}